#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "../include/cpu_monitor.h"

#define PROC_STAT "/proc/stat"
#define MAX_LINE_LENGTH 256

static pthread_t monitor_thread;
static CPU_Usage current_usage = {0};
static pthread_mutex_t usage_mutex = PTHREAD_MUTEX_INITIALIZER;
static CPU_Monitor_Args* monitor_args = NULL;  // 添加全局变量

// 读取CPU时间统计
static int read_cpu_times(unsigned long long* times) {
    FILE* fp;
    char line[MAX_LINE_LENGTH];
    
    fp = fopen(PROC_STAT, "r");
    if (!fp) {
        return -1;
    }

    if (!fgets(line, sizeof(line), fp)) {
        fclose(fp);
        return -1;
    }

    // 解析CPU时间统计
    sscanf(line, "cpu %llu %llu %llu %llu %llu %llu %llu",
           &times[0], &times[1], &times[2], &times[3],
           &times[4], &times[5], &times[6]);

    fclose(fp);
    return 0;
}

// 计算CPU使用率
static void calculate_cpu_usage(unsigned long long* prev_times, unsigned long long* curr_times) {
    unsigned long long total_diff = 0;
    unsigned long long idle_diff = 0;
    
    // 计算总时间差
    for (int i = 0; i < 7; i++) {
        total_diff += curr_times[i] - prev_times[i];
    }
    
    // 计算空闲时间差
    idle_diff = curr_times[3] - prev_times[3];
    
    // 计算使用率
    double total_usage = 100.0 * (1.0 - ((double)idle_diff / total_diff));
    double user_usage = 100.0 * ((double)(curr_times[0] - prev_times[0]) / total_diff);
    double system_usage = 100.0 * ((double)(curr_times[2] - prev_times[2]) / total_diff);
    
    // 更新当前使用率
    pthread_mutex_lock(&usage_mutex);
    current_usage.total = total_usage;
    current_usage.user = user_usage;
    current_usage.system = system_usage;
    current_usage.idle = 100.0 - total_usage;
    pthread_mutex_unlock(&usage_mutex);
}

// CPU监控线程函数
void* cpu_monitor_thread(void* arg) {
    CPU_Monitor_Args* args = (CPU_Monitor_Args*)arg;
    unsigned long long prev_times[7] = {0};
    unsigned long long curr_times[7] = {0};
    
    // 首次读取CPU时间
    if (read_cpu_times(prev_times) < 0) {
        return NULL;
    }
    
    while (args->running) {
        sleep(args->interval);
        
        // 读取当前CPU时间
        if (read_cpu_times(curr_times) < 0) {
            continue;
        }
        
        // 计算CPU使用率
        calculate_cpu_usage(prev_times, curr_times);
        
        // 更新上一次的时间
        memcpy(prev_times, curr_times, sizeof(prev_times));
    }
    
    return NULL;
}

// 初始化CPU监控
int init_cpu_monitor(void) {
    monitor_args = malloc(sizeof(CPU_Monitor_Args));
    if (!monitor_args) {
        return -1;
    }
    
    monitor_args->interval = 1;  // 默认1秒更新一次
    monitor_args->running = 1;
    
    if (pthread_create(&monitor_thread, NULL, cpu_monitor_thread, monitor_args) != 0) {
        free(monitor_args);
        monitor_args = NULL;
        return -1;
    }
    
    return 0;
}

// 清理CPU监控
void cleanup_cpu_monitor(void) {
    if (monitor_args) {
        monitor_args->running = 0;  // 设置停止标志
        pthread_join(monitor_thread, NULL);  // 等待线程结束
        free(monitor_args);
        monitor_args = NULL;
    }
    
    pthread_mutex_destroy(&usage_mutex);
}

// 获取当前CPU使用率
CPU_Usage get_cpu_usage(void) {
    CPU_Usage usage;
    
    pthread_mutex_lock(&usage_mutex);
    usage = current_usage;
    pthread_mutex_unlock(&usage_mutex);
    
    return usage;
} 